<template>
  <div class="version-association-manager">
    <div class="manager-header">
      <div class="header-left">
        <h3>{{ title }}</h3>
        <p class="description">{{ description }}</p>
      </div>
      <div class="header-actions">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="showAddDialog = true"
          v-if="!readonly"
        >
          添加关联
        </el-button>
        <el-button 
          :icon="Refresh" 
          @click="fetchAssociations"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 关联类型标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane 
        v-for="type in associationTypes" 
        :key="type.key"
        :label="type.label"
        :name="type.key"
      >
        <template #label>
          <div class="tab-label">
            <el-icon><component :is="type.icon" /></el-icon>
            <span>{{ type.label }}</span>
            <el-badge 
              :value="getAssociationCount(type.key)" 
              :hidden="getAssociationCount(type.key) === 0"
              class="tab-badge"
            />
          </div>
        </template>
        
        <!-- 关联项列表 -->
        <div class="association-content">
          <div class="content-toolbar" v-if="!readonly">
            <el-input
              v-model="searchText"
              placeholder="搜索关联项..."
              clearable
              style="width: 300px"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <div class="toolbar-actions">
              <el-button 
                type="text" 
                @click="selectAll(type.key)"
                v-if="getFilteredAssociations(type.key).length > 0"
              >
                全选
              </el-button>
              <el-button 
                type="text" 
                @click="clearSelection"
                v-if="selectedItems.length > 0"
              >
                取消选择
              </el-button>
              <el-button 
                type="danger" 
                :icon="Delete"
                @click="batchRemove"
                v-if="selectedItems.length > 0"
              >
                批量移除
              </el-button>
            </div>
          </div>
          
          <div class="association-list" v-loading="loading">
            <el-empty 
              v-if="getFilteredAssociations(type.key).length === 0"
              :description="`暂无${type.label}关联`"
            />
            
            <div 
              v-for="item in getFilteredAssociations(type.key)"
              :key="item.id"
              class="association-item"
              :class="{ 'selected': selectedItems.includes(item.id) }"
              @click="toggleSelection(item.id)"
            >
              <div class="item-checkbox" v-if="!readonly">
                <el-checkbox 
                  :model-value="selectedItems.includes(item.id)"
                  @change="toggleSelection(item.id)"
                />
              </div>
              
              <div class="item-content">
                <div class="item-header">
                  <div class="item-title">
                    <el-link 
                      :href="getItemLink(item)" 
                      target="_blank"
                      class="item-name"
                    >
                      {{ item.title || item.name }}
                    </el-link>
                    <AssociationStatusTag 
                      :type="type.key" 
                      :status="item.status"
                      size="small"
                    />
                  </div>
                  <div class="item-meta">
                    <span class="item-id">#{{ item.number || item.id }}</span>
                    <span class="item-project">{{ item.project_name }}</span>
                    <span class="item-assignee" v-if="item.assignee_name">
                      负责人：{{ item.assignee_name }}
                    </span>
                  </div>
                </div>
                
                <div class="item-description" v-if="item.description">
                  {{ item.description }}
                </div>
                
                <div class="item-footer">
                  <div class="item-dates">
                    <span v-if="item.created_at">
                      创建：{{ formatDate(item.created_at) }}
                    </span>
                    <span v-if="item.due_date">
                      截止：{{ formatDate(item.due_date) }}
                    </span>
                  </div>
                  
                  <div class="item-actions" v-if="!readonly">
                    <el-button 
                      type="text" 
                      size="small"
                      @click.stop="viewDetail(item)"
                    >
                      查看
                    </el-button>
                    <el-button 
                      type="text" 
                      size="small"
                      @click.stop="editAssociation(item)"
                    >
                      编辑
                    </el-button>
                    <el-button 
                      type="text" 
                      size="small"
                      @click.stop="removeAssociation(item)"
                    >
                      移除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-wrapper" v-if="pagination[type.key]">
            <el-pagination
              v-model:current-page="pagination[type.key].page"
              v-model:page-size="pagination[type.key].pageSize"
              :total="pagination[type.key].total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="fetchAssociations"
              @current-change="fetchAssociations"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加关联对话框 -->
    <el-dialog
      v-model="showAddDialog"
      title="添加关联"
      width="800px"
      @close="resetAddForm"
    >
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="关联类型">
          <el-select 
            v-model="addForm.type" 
            placeholder="选择关联类型"
            @change="handleTypeChange"
          >
            <el-option
              v-for="type in associationTypes"
              :key="type.key"
              :label="type.label"
              :value="type.key"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="搜索项目">
          <el-input
            v-model="addForm.searchText"
            placeholder="输入关键词搜索..."
            @input="searchAvailableItems"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="可选项目">
          <div class="available-items" v-loading="searchLoading">
            <el-empty 
              v-if="availableItems.length === 0"
              description="暂无可选项目"
            />
            
            <div 
              v-for="item in availableItems"
              :key="item.id"
              class="available-item"
              :class="{ 'selected': addForm.selectedIds.includes(item.id) }"
              @click="toggleAddSelection(item.id)"
            >
              <el-checkbox 
                :model-value="addForm.selectedIds.includes(item.id)"
                @change="toggleAddSelection(item.id)"
              />
              <div class="item-info">
                <div class="item-title">{{ item.title || item.name }}</div>
                <div class="item-meta">
                  <span>#{{ item.number || item.id }}</span>
                  <span>{{ item.project_name }}</span>
                  <AssociationStatusTag 
                    :type="addForm.type" 
                    :status="item.status"
                    size="small"
                  />
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="addAssociations"
            :disabled="addForm.selectedIds.length === 0"
            :loading="adding"
          >
            添加关联 ({{ addForm.selectedIds.length }})
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Delete,
  Document,
  Warning,
  User
} from '@element-plus/icons-vue'
import { versionAPI } from '@/api/version'
import { formatDate } from '@/utils/date'
import { debounce } from '@/utils/common'
import AssociationStatusTag from './AssociationStatusTag.vue'

interface Props {
  versionId: string
  title?: string
  description?: string
  readonly?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  title: '版本关联管理',
  description: '管理版本与任务、缺陷、需求等的关联关系',
  readonly: false
})

const emit = defineEmits<{
  'association-change': [type: string, count: number]
}>()

const router = useRouter()

// 关联类型配置
const associationTypes = [
  {
    key: 'tasks',
    label: '任务',
    icon: Document
  },
  {
    key: 'bugs',
    label: '缺陷',
    icon: Warning
  },
  {
    key: 'requirements',
    label: '需求',
    icon: User
  }
]

// 响应式数据
const loading = ref(false)
const adding = ref(false)
const searchLoading = ref(false)
const activeTab = ref('tasks')
const searchText = ref('')
const selectedItems = ref<string[]>([])
const showAddDialog = ref(false)

// 关联数据
const associations = reactive<Record<string, any[]>>({
  tasks: [],
  bugs: [],
  requirements: []
})

// 分页数据
const pagination = reactive<Record<string, any>>({
  tasks: { page: 1, pageSize: 10, total: 0 },
  bugs: { page: 1, pageSize: 10, total: 0 },
  requirements: { page: 1, pageSize: 10, total: 0 }
})

// 添加表单
const addForm = reactive({
  type: 'tasks',
  searchText: '',
  selectedIds: [] as string[]
})

const availableItems = ref<any[]>([])

// 计算属性
const getAssociationCount = (type: string) => {
  return associations[type]?.length || 0
}

const getFilteredAssociations = (type: string) => {
  const items = associations[type] || []
  if (!searchText.value) return items
  
  const keyword = searchText.value.toLowerCase()
  return items.filter(item => 
    (item.title || item.name || '').toLowerCase().includes(keyword) ||
    (item.description || '').toLowerCase().includes(keyword) ||
    (item.number || item.id || '').toString().includes(keyword)
  )
}

// 监听器
watch(() => props.versionId, () => {
  if (props.versionId) {
    fetchAssociations()
  }
}, { immediate: true })

// 方法
const fetchAssociations = async () => {
  if (!props.versionId) return
  
  try {
    loading.value = true
    
    // 获取所有类型的关联数据
    for (const type of associationTypes) {
      const params = {
        skip: (pagination[type.key].page - 1) * pagination[type.key].pageSize,
        limit: pagination[type.key].pageSize
      }
      
      const response = await versionAPI.getVersionAssociations(
        props.versionId, 
        type.key as 'task' | 'defect' | 'requirement', 
        params
      )
      
      if (response.success && response.data) {
        associations[type.key] = response.data.items || []
        pagination[type.key].total = response.data.pagination?.total || 0
      } else {
        associations[type.key] = []
        pagination[type.key].total = 0
      }
      
      // 发出关联变化事件
      emit('association-change', type.key, response.data.total)
    }
  } catch (error) {
    console.error('获取关联数据失败:', error)
    ElMessage.error('获取关联数据失败')
  } finally {
    loading.value = false
  }
}

const handleTabChange = (tabName: string) => {
  activeTab.value = tabName
  selectedItems.value = []
  searchText.value = ''
}

const handleSearch = debounce(() => {
  // 搜索逻辑已在计算属性中实现
}, 300)

const toggleSelection = (itemId: string) => {
  const index = selectedItems.value.indexOf(itemId)
  if (index > -1) {
    selectedItems.value.splice(index, 1)
  } else {
    selectedItems.value.push(itemId)
  }
}

const selectAll = (type: string) => {
  const items = getFilteredAssociations(type)
  selectedItems.value = items.map(item => item.id)
}

const clearSelection = () => {
  selectedItems.value = []
}

const getItemLink = (item: any) => {
  // 根据类型生成链接
  const baseUrl = window.location.origin
  switch (activeTab.value) {
    case 'tasks':
      return `${baseUrl}/tasks/${item.id}`
    case 'bugs':
      return `${baseUrl}/bugs/${item.id}`
    case 'requirements':
      return `${baseUrl}/requirements/${item.id}`
    default:
      return '#'
  }
}

const viewDetail = (item: any) => {
  // 跳转到详情页面
  switch (activeTab.value) {
    case 'tasks':
      router.push(`/tasks/${item.id}`)
      break
    case 'bugs':
      router.push(`/bugs/${item.id}`)
      break
    case 'requirements':
      router.push(`/requirements/${item.id}`)
      break
  }
}

const editAssociation = (item: any) => {
  // 编辑关联关系
  ElMessage.info('编辑功能开发中...')
}

const removeAssociation = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除与"${item.title || item.name}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await versionAPI.removeVersionAssociation(
      props.versionId,
      activeTab.value as 'task' | 'defect' | 'requirement',
      item.id
    )
    
    if (!response.success) {
      throw new Error(response.message || '移除关联失败')
    }
    
    ElMessage.success('移除成功')
    fetchAssociations()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除关联失败:', error)
      ElMessage.error('移除关联失败')
    }
  }
}

const batchRemove = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量移除 ${selectedItems.value.length} 个关联吗？`,
      '批量移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 批量移除关联
    for (const itemId of selectedItems.value) {
      const response = await versionAPI.removeVersionAssociation(
        props.versionId,
        activeTab.value as 'task' | 'defect' | 'requirement',
        itemId
      )
      
      if (!response.success) {
        throw new Error(response.message || '移除关联失败')
      }
    }
    
    ElMessage.success('批量移除成功')
    selectedItems.value = []
    fetchAssociations()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量移除失败:', error)
      ElMessage.error('批量移除失败')
    }
  }
}

// 添加关联相关方法
const handleTypeChange = () => {
  addForm.selectedIds = []
  availableItems.value = []
  addForm.searchText = ''
}

const searchAvailableItems = debounce(async () => {
  if (!addForm.searchText.trim()) {
    availableItems.value = []
    return
  }
  
  try {
    searchLoading.value = true
    
    // 根据类型搜索可用项目
    const response = await versionAPI.searchAssociationItems(
      addForm.type as 'task' | 'defect' | 'requirement',
      {
        search: addForm.searchText,
        exclude_version_id: props.versionId,
        limit: 50
      }
    )
    
    if (response.success && response.data) {
      availableItems.value = response.data.items || []
    } else {
      availableItems.value = []
    }
  } catch (error) {
    console.error('搜索可用项目失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    searchLoading.value = false
  }
}, 300)

const toggleAddSelection = (itemId: string) => {
  const index = addForm.selectedIds.indexOf(itemId)
  if (index > -1) {
    addForm.selectedIds.splice(index, 1)
  } else {
    addForm.selectedIds.push(itemId)
  }
}

const addAssociations = async () => {
  try {
    adding.value = true
    
    const response = await versionAPI.addVersionAssociations(
      props.versionId,
      addForm.type as 'task' | 'defect' | 'requirement',
      addForm.selectedIds
    )
    
    if (!response.success) {
      throw new Error(response.message || '添加关联失败')
    }
    
    ElMessage.success('添加关联成功')
    showAddDialog.value = false
    fetchAssociations()
  } catch (error) {
    console.error('添加关联失败:', error)
    ElMessage.error('添加关联失败')
  } finally {
    adding.value = false
  }
}

const resetAddForm = () => {
  Object.assign(addForm, {
    type: 'tasks',
    searchText: '',
    selectedIds: []
  })
  availableItems.value = []
}

// 生命周期
onMounted(() => {
  if (props.versionId) {
    fetchAssociations()
  }
})
</script>

<style scoped>
.version-association-manager {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.header-left h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
}

.tab-badge {
  margin-left: 4px;
}

.association-content {
  padding: 16px;
}

.content-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.toolbar-actions {
  display: flex;
  gap: 8px;
}

.association-list {
  min-height: 200px;
}

.association-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.association-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.association-item.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.item-checkbox {
  flex-shrink: 0;
  margin-top: 2px;
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-header {
  margin-bottom: 8px;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.item-name {
  font-weight: 500;
  font-size: 15px;
}

.item-meta {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.item-id {
  font-weight: 500;
  color: #606266;
}

.item-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-dates {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.item-actions {
  display: flex;
  gap: 4px;
}

.pagination-wrapper {
  margin-top: 16px;
  text-align: right;
}

.available-items {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 6px;
}

.available-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.available-item:hover {
  background-color: #f5f7fa;
}

.available-item.selected {
  background-color: #f0f9ff;
}

.available-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
  min-width: 0;
}

.item-info .item-title {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-info .item-meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

@media (max-width: 768px) {
  .manager-header {
    flex-direction: column;
    gap: 16px;
  }

  .content-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .association-item {
    flex-direction: column;
    gap: 8px;
  }

  .item-footer {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .item-actions {
    align-self: flex-end;
  }
}
</style>